﻿using MediatR;
using PublicClass;
using S.Services.SheepMale.Domain.PurchaseSales;
using S.Services.SheepMale.Infrastructure;
using S.Services.SheepMale.Read.Api.Application.ReadCommand.ReadSheepMaleCommand;

namespace S.Services.SheepMale.Read.Api.Application.ReadCommandHandler.ReadSheepMaleCommandHandler
{
    public class ShowFatherCommandHandler : IRequestHandler<ShowFatherCommand, PageInfo<SheepMaleInfo>>
    {
        private readonly IRepository<SheepMaleInfo> repository;

        private readonly PageInfo<SheepMaleInfo> pageInfo;
        public ShowFatherCommandHandler(IRepository<SheepMaleInfo> repository, PageInfo<SheepMaleInfo> pageInfo)
        {
            this.repository = repository;
            this.pageInfo = pageInfo;
        }

        public async Task<PageInfo<SheepMaleInfo>> Handle(ShowFatherCommand request, CancellationToken cancellationToken)
        {
            var result = repository.AllAsync().Result.Where(x => x.SheepType == request.sheepType && x.IsDel == false);
            if (request.FatherEarTag != null)
            {
                result = result.Where(x => x.Earbugles.Contains(request.FatherEarTag)).AsQueryable();
            }
            pageInfo.totalCount = result.Count();
            pageInfo.pageCount = (int)Math.Ceiling(pageInfo.totalCount * 1.0 / request.pageSize);
            pageInfo.datas = result.OrderByDescending(x => x.CreateDate).Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();
            return pageInfo;
        }
    }
}
